<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="姓名：">
              <a-input placeholder="请输入姓名" v-model="queryParam.employeeName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="人员状态：">
                <j-dict-select-tag
                  placeholder="请选择人员状态"
                  style="radio"
                  v-model="queryParam.employeeStatus"
                  dictCode="employee_status"
                />
              </a-form-item>
            </a-col>
          <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="所属岗位：">
                <j-dict-select-tag  type="list" v-model="queryParam.mainPost"
                                     dictCode="sys_position,name,id,del_flag = 0 and audit_status=2" placeholder="请选择所属岗位"/>
              </a-form-item>
            </a-col> -->
          <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="所属部门：">
              <j-select-depart :disabled="false" v-model="queryParam.employeedepartmentId" />
            </a-form-item>
          </a-col> -->
          <!-- <template v-if="toggleSearchStatus"> -->
            <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="所属团队：">
                <select-team-input  v-model="queryParam.teamId" :tdlx="3" />
              </a-form-item>
            </a-col> -->
            <!--            <a-col :xl="6" :lg="7" :md="8" :sm="24">-->
            <!--              <a-form-item label="所属期间：">-->
            <!--                <a-input placeholder="请输入所属期间" v-model="queryParam.period"></a-input>-->
            <!--              </a-form-item>-->
            <!--            </a-col>-->
          <!-- </template> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!--      <a-button @click="handleAdd" type="primary" icon="plus" :disabled="isDisabledAuth('erpPayrollManagement:add')">新增</a-button>-->
      <a-button
        type="primary"
        icon="download"
        @click="handleExportXls('工资条管理表')"
        :disabled="isDisabledAuth('erpPayrollManagement:export')"
        >导出</a-button
      >
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
      >
<!--        <a-button type="primary" icon="import" :disabled="isDisabledAuth('erpPayrollManagement:import')">导入</a-button>-->
      </a-upload>
      <!-- 高级查询区域 -->
      <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="handcalculatelist(selectedRowKeys)" :disabled="isDisabledAuth('erpPayrollManagement:handcalculatelist')"
            ><a-icon type="unordered-list" />批量生成</a-menu-item
          >
          <a-menu-item key="2" @click="correlationlist(selectedRowKeys)" :disabled="isDisabledAuth('erpPayrollManagement:correlationlist')"
            ><a-icon type="to-top" />批量关联</a-menu-item
          >
          <a-menu-item key="3" @click="freezes(selectedRowKeys)" :disabled="isDisabledAuth('erpPayrollManagement:freezes')"
            ><a-icon type="lock" />批量冻结</a-menu-item
          >
           <a-menu-item key="4" @click="nofreezes(selectedRowKeys)" :disabled="isDisabledAuth('erpPayrollManagement:nofreezes')"
            ><a-icon type="unlock" />批量解冻</a-menu-item
          >
          <!--          <a-menu-item key="4" @click="batchCounterTrial" :disabled="isDisabledAuth('erpPayrollManagement:counterTrial')"><a-icon type="rollback" />反审</a-menu-item>-->
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
      <a-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <a-row>
              <template v-for="(item, index) in defColumns">
                <template v-if="item.key != 'rowIndex' && item.dataIndex != 'action'">
                  <a-col :span="12"
                    ><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col
                  >
                </template>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>
        <a style="float: right"><a-icon type="setting" :style="iconStyle" /></a>
      </a-popover>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        :components="draggableComponent"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        :customRow="customRow"
        @change="handleTableChange"
      >
        <template slot="status" slot-scope="status">
          <a-badge :status="status | statusTypeFilter" :text="status | statusFilter" />
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <div class="all_button" slot="action" slot-scope="text, record">
          <div class="all_top">
            <template v-if="record.freezeStatus=='2' && record.relevanceStatus=='1' && record.payGradeId_dictText">
              <a-popconfirm title="确定生成吗?" @confirm="() => handcalculate(record)">
                <a-button type="primary" size="small" :disabled="isDisabledAuth('erpPayrollManagement:calculate')"
                  >生成</a-button
                >
              </a-popconfirm>
            </template>
            <template v-if="record.freezeStatus=='2'">
              <a-button style="margin-left:10px" type="primary" size="small" @click="correlation(record)" :disabled="isDisabledAuth('erpPayrollManagement:correlation')"
                  >关联模型</a-button
                >

            </template>
            <template v-if="record.freezeStatus=='2'">
              <a-button type="primary" style="margin-left:10px" size="small" @click="inspect(record.employeeId)" :disabled="isDisabledAuth('erpPayrollManagement:checkup')"
                  >检查</a-button
                >
            </template>
            <template v-if="record.freezeStatus=='1'">
              <a-popconfirm title="确定解冻吗?" @confirm="() => nofreeze(record.id)">
                <a-button type="primary" size="small" :disabled="isDisabledAuth('erpPayrollManagement:nofreeze')"
                  >解冻</a-button
                >
              </a-popconfirm>
          </template>
          </div>
          <div class="all_bottom">
            <template v-if="record.freezeStatus=='2'">
              <a-popconfirm title="确定冻结吗?" @confirm="() => freeze(record.id)">
                <a-button type="primary" size="small" :disabled="isDisabledAuth('erpPayrollManagement:freeze')"
                  >冻结</a-button
                >
              </a-popconfirm>
            </template>
            <a-button type="primary" size="small" @click="handleEdit(record)" :disabled="isDisabledAuth('erpPayrollManagement:edit')"  v-if="record.freezeStatus=='2'">编辑</a-button>
          </div>


        </div>
        <a slot="name" slot-scope="text, record" @click="skip(record.employeeId)">{{ text }}</a>
        <a slot="netPayment" slot-scope="text, record" @click="payment(record)">{{ text==null?0:text }}</a>

        <span slot="produceStatus" slot-scope="text, record">{{text=='1'?'已生成':'未生成'}}</span>

        <span slot="period" slot-scope="text, record">{{new Date().getFullYear()+'-'+new Date().getMonth()}}</span>


      </a-table>

    </div>

    <a-modal v-model="visible" title="关联薪酬模型" @ok="handleOk()" :bodyStyle ="{
                'height':'200px',
                'display':'flex',
                'justifyContent': 'center',
                'alignItems': 'center'
              }">
      <j-dict-select-tag type="list" v-model="erpSalaryModel"
               dictCode="erp_salary_model_management,name,id,del_flag = 0 and audit_status=2" style="width: 300px;" placeholder="请选择薪酬模型"/>
    </a-modal>


<!--    批量关联-->
    <a-modal v-model="visiblelist" title="关联薪酬模型" @ok="handlelistOk()" :bodyStyle ="{
                'height':'200px',
                'display':'flex',
                'justifyContent': 'center',
                'alignItems': 'center'
              }">
    <j-dict-select-tag type="list" v-model="erpSalaryModellist"
             dictCode="erp_salary_model_management,name,id,del_flag = 0 and audit_status=2" style="width: 300px;" placeholder="请选择薪酬模型"/>

    </a-modal>


    <a-modal v-model="detection" title="提示信息" @ok="detectionHandleOk" :bodyStyle ="{
        'height':'200px',
        'display':'flex',
        'justifyContent': 'center',
        'alignItems': 'center'
      }">
      <a-alert
        v-if="inspectFlag"
        message="检查异常："
        description="您未关联模型，将无法生成工资条，请联系HR处理！"
        type="warning"
        show-icon
      />
      <a-alert
        v-else
        message="检查成功！信息如下："
        :description="`当前关联模型${modelName}。`"
        type="success"
        show-icon
      />
      <template slot="footer">
        <a-button @click.stop="()=>{detection=false}">关闭</a-button>
      </template>
    </a-modal>


    <erp-payroll-management-modal ref="modalForm" @ok="modalFormOk"></erp-payroll-management-modal>
    <erp-payroll-ledger-modal ref="payrollLedger"></erp-payroll-ledger-modal>
    <audit-modal ref="auditModal" @ok="modalFormOk"></audit-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import ErpPayrollManagementModal from './modules/ErpPayrollManagementModal'
import ErpPayrollLedgerModal from './modules/ErpPayrollLedgerModal'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import {getAction, httpAction} from '@api/manage'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput';
import { postAction } from '@api/manage'

export default {
  name: 'ErpPayrollManagementList',
  mixins: [JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
  components: {
    ErpPayrollManagementModal,
    ErpPayrollLedgerModal,
    SelectTeamInput
  },
  data() {
    return {
      date: new Date().getFullYear(),
      description: '工资条管理表管理页面',
      visible: false,
      detection: false,
      inspectFlag: false,
      erpSalaryModel: null,
      modelName: null,
      modelId: null,
      selectedRowKeysdata: null,
      visiblelist:null,
      erpSalaryModellist:null,
      byIds: null,
      //表头
      columns: [],
      //列设置
      settingColumns: [],
      // 列定义
      defColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '姓名',
          align: 'center',
          width: 100,
          dataIndex: 'employeeName',
          scopedSlots: { customRender: 'name' },
        },
        // {
        //   title: '所属公司',
        //   align: 'center',
        //   dataIndex: 'company',
        // },
        // {
        //   title: '所属部门',
        //   align: 'center',
        //   dataIndex: 'employeedepartmentId_dictText',
        // },
        // {
        //   title: '所属团队',
        //   align: 'center',
        //   dataIndex: 'teamId_dictText',
        // },
        {
          title: '所属岗位',
          align: 'center',
          width: 200,
          dataIndex: 'mainPost',
        },
        {
          title: '转正时间',
          width: 200,
          align: 'center',
          dataIndex: 'probationEndDate',
        },
        {
          title: '所属期间',
          align: 'center',
          width: 100,
          dataIndex: 'period',
          scopedSlots: { customRender: 'period' },
        },
        {
          title: '关联状态',
          align: 'center',
          width: 100,
          dataIndex: 'relevanceStatus_dictText',
        },
        {
          title: '生成状态',
          align: 'center',
          width: 100,
          dataIndex: 'produceStatus',
          scopedSlots: { customRender: 'produceStatus' },
        },
        {
          title: '冻结状态',
          align: 'center',
          width: 100,
          dataIndex: 'freezeStatus_dictText',
        },
        {
          title: '薪级',
          align: 'center',
          width: 100,
          sorter: (a, b) => a.payGradeId_dictText - b.payGradeId_dictText,
          dataIndex: 'payGradeId_dictText',
        },
        {
          title: '实发工资（元）',
          align: 'center',
          width: 200,
          sorter: (a, b) => a.netPayment - b.netPayment,
          dataIndex: 'netPayment',
          scopedSlots: { customRender: 'netPayment' },
        },
        {
          title: '关联模型',
          align: 'center',
          width: 200,
          dataIndex: 'modelsId_dictText',
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action',
          },
        },
      ],
      url: {
        list: '/api/erp/hr/payment/erpPayrollManagement/listnew',
        delete: '/api/erp/hr/payment/erpPayrollManagement/delete',
        deleteBatch: '/api/erp/hr/payment/erpPayrollManagement/deleteBatch',
        exportXlsUrl: '/api/erp/hr/payment/erpPayrollManagement/exportXls',
        importExcelUrl: 'hr/payment/erpPayrollManagement/importExcel',
        submit: '/api/erp/hr/payment/erpPayrollManagement/submit',
        submitBatch: '/api/erp/hr/payment/erpPayrollManagement/submitBatch',
        revoke: '/api/erp/hr/payment/erpPayrollManagement/revoke',
        revokeBatch: '/api/erp/hr/payment/erpPayrollManagement/revokeBatch',
        counterTrial: '/api/erp/hr/payment/erpPayrollManagement/counterTrial',
        counterTrialBatch: '/api/erp/hr/payment/erpPayrollManagement/counterTrialBatch',
        audit: '/api/erp/hr/payment/erpPayrollManagement/audit',
        auditBatch: '/api/erp/hr/payment/erpPayrollManagement/auditBatch',
        overrule: '/api/erp/hr/payment/erpPayrollManagement/overrule',
        overruleBatch: '/api/erp/hr/payment/erpPayrollManagement/overruleBatch',
        queryEmployeeById: '/api/erp/files/employee/erpEmployeeFile/queryPageById',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    inspect(item) {

      this.checkup(item);

      this.detection = true
    },
    detectionHandleOk(e) {
      this.detection = false;
    },
    correlation(item) {
      this.visible = true

      this.modelId = item.id;

      this.erpSalaryModel = item.modelsId;
    },
    handleOk() {
      this.visible = false;
      this.association(this.modelId,this.erpSalaryModel);
    },

    handlelistOk(){
      this.visiblelist = false;
      this.associations(this.selectedRowKeysdata,this.erpSalaryModellist)
    },

    correlationlist(item) {
      console.log(item)
      this.visiblelist = true
      this.selectedRowKeysdata = item
    },

    initDictConfig() {},
    skip(employeeFileId) {
      let that=this
      getAction(this.url.queryEmployeeById,{ id: employeeFileId }).then(res => {
        if(res.success){
          let data=res.result.records;
          console.log(data);
          if(data){
            that.$router.push({
              path: '/schedule',
              query: {
                id: employeeFileId,
                applyId: data[0].applyId
              }
            }) 
          }
        }
      })
    },
    payment(record) {
      this.$refs.payrollLedger.edit(record)
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'BigDecimal', value: 'basePay', text: '基础工资', dictCode: '' })

      this.superFieldList = fieldList
    },

    //检查
    checkup(val) {
      getAction('/api/erp/hr/payment/erpPayrollManagement/checkup', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          if(data == "您未关联模型"){
            this.inspectFlag=true;
          }else{
            this.inspectFlag=false;
            this.modelName = data;
          }
        }
      })
    },
    //关联模型
    association(id,modelsId) {
      getAction('/api/erp/hr/payment/erpPayrollManagement/association', { id: id , modelsId: modelsId} ).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$message.success(data);
          this.loadData();
        }else{
          this.$message.error(res.message);
        }
      })
    },
    //生成
    handcalculate(val) {
      httpAction('/api/erp/hr/payment/erpPayrollManagement/handcalculate',  val ,'post').then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$message.success(data);
          this.loadData();
        }else{
          this.$message.error(res.message);
        }
      })
    },
    //冻结
    freeze(val) {
      getAction('/api/erp/hr/payment/erpPayrollManagement/freeze', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$message.success(data);
          this.loadData();
        }else{
          this.$message.error(res.message);
        }
      })
    },

    //批量冻结
    freezes(val) {
      getAction('/api/erp/hr/payment/erpPayrollManagement/freezes', {ids : val.toString()}).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$message.success(data);
          this.loadData();
        }else{
          this.$message.error(res.message);
        }
      })
    },

    //解冻
    nofreeze(val) {
      getAction('/api/erp/hr/payment/erpPayrollManagement/nofreeze', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$message.success(data);
          this.loadData();
        }else{
          this.$message.error(res.message);
        }
      })
    },

    //批量解冻
    nofreezes(val) {
      getAction('/api/erp/hr/payment/erpPayrollManagement/nofreezes', {ids : val.toString()}).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$message.success(data);
          this.loadData();
        }else{
          this.$message.error(res.message);
        }
      })
    },


    // 批量生成
    handcalculatelist(ops) {
      //根据 工资条的id 获取 薪酬信息
      getAction('/api/erp/hr/payment/erpPayrollManagement/handcalculatelist', {ids:ops.toString()}).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$message.success(data);
          this.loadData();
        }else{
          this.$message.error(res.message);
        }
      })
    },
    //批量关联模型
    associations(val1,val2) {
      getAction('/api/erp/hr/payment/erpPayrollManagement/associations', {ids:val1.toString(),modelsId: val2}).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$message.success(data);
          this.loadData();
        }else{
          this.$message.error(res.message);
        }
      })
    },
    
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.all_bottom {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
}
</style>
